You are here: Home â•— Javascript Tutor â•— Lesson 18 | |
![]() | |
![]() |
![]() |
![]() |
Math
Javascript has a "Math" object. It is used whenever we want to do anything more than simple arithmetic. It's basic syntax is Math.method(number). I know it's a little confusing at first... bear with me.
Look at this simple script that calculates square root...
<HTML> <HEAD> <TITLE></TITLE> <SCRIPT language="Javascript"><!-- function mySquareRoot() { mynumber = Math.sqrt(9); alert(mynumber); } //--></SCRIPT> </HEAD> <BODY> <A HREF="javascript:mySquareRoot()">Click here</A> </BODY> </HTML> |
See what's going on here? It's not too hard at all.
Exercise: Alter the last example to throw up a prompt box that requests a number. Calculate the square root then throw an alert box up that says something like "The square root of 9 is 3"
Here's another Math method...
Math.round()
It, uh, rounds a number to the nearest integer. (Aren't you glad you got me around to explain things?)
Exercise: Modify the last exercise to round whatever number you feed it.
Exercise: Combine the two methods to get the square root of a number then present it in rounded form. Then, and this is a little tough, determine if the number has in fact been rounded and give a different message depending on whether it's rounded or not. Let me explain further. The square root of 9 rounded is 3. It's exactly 3. The square root of 10 is 3.3333... The square root of 10 rounded is around 3. So, I want you to alter the function so that if the user enters 9 it says...
The square root of 9 is exactly 3.
If the user enters 10 I want it to say...
The square root of 10 rounds to about 3.
You are going to have to do two things. One, find a way to determine if it rounds evenly or not. And two, you're going to have to stick an if-else statement in there to deal with the two possible outputs. Good luck and persevere until you figure it out.
There are other Math methods...
Math.floor() rounds down. Math.floor(3.2) is 3. Math.floor(3.9) is 3.
Math.ceil() rounds up. Math.ceil(3.2) is 4. Math.ceil(3.9) is 4.
Math.round() by the way would round anything less than 3.5 to 3 and 3.5 or greater to 4.
How to round to the nearest tenth? Quite simple really... multiply a number by 10, round it, then divide by 10.
There is Math.sin(), Math.cos(), etc. There is Math.max() (hey, wasn't that a movie with Mel Gibson?) Math.max(x,y) returns the greater of two numbers.
alert(Math.max(2,8)); will pop up 8. Conversely, alert(Math.min(2,8)); will pop up 2.
There are a few others and, especially if you're a math person, I encourage you to study further.
<< BACK NEXT >> |
![]() |
![]() |
Javascript Reference irt.org/Javascript FAQ Deja Power Search ![]() |
![]() |
Print version available - Get the PageTutor book & CD |
![]() |
![]() |
|
|